import type { Reducer } from "react";
import { useEffect, useReducer } from "react";

export enum SmsCodeStatus {
  default, // 默认状态
  startCountDown, // 开始倒计时状态
  countDowning, // 倒计时中状态
  endCountDown, // 倒计时结束状态
}

interface SmsCodeState {
  status: SmsCodeStatus;
  count: number;
}

type Actions = "startCountDown" | "countDowning" | "endCountDown";

const useSmsCode = () => {
  const [state, dispatch] = useReducer<
    Reducer<SmsCodeState, { type: Actions }>
  >(
    // eslint-disable-next-line @typescript-eslint/no-shadow
    (state, action) => {
      switch (action.type) {
        case "startCountDown":
          return {
            count: 60,
            status: SmsCodeStatus.startCountDown,
          };
        case "endCountDown":
          return {
            ...state,
            status: SmsCodeStatus.endCountDown,
          };
        case "countDowning":
          return {
            ...state,
            count: state.count - 1,
          };
        default:
          return state;
      }
    },
    { status: SmsCodeStatus.default, count: 0 }
  );

  useEffect(() => {
    if (
      [SmsCodeStatus.startCountDown, SmsCodeStatus.countDowning].includes(
        state.status
      )
    ) {
      if (state.count <= 0) {
        dispatch({ type: "endCountDown" });
        return;
      }

      const timer = setInterval(() => {
        dispatch({ type: "countDowning" });
      }, 1000);
      return () => clearInterval(timer);
    }
  }, [state]);

  return {
    smsCodeState: state,
    dispatch,
  };
};

export default useSmsCode;
